<?php

class SiteController extends Controller
{
    public $layout = '//layouts/front-end';
    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }


    /**
     * Declares class-based actions.
     */
    public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }
    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index','view','listIdeality'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('create','update','CreateOrder','Transaction','ConfirmOrder','PastIdeality','message','Download'),
                'users'=>array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('admin','delete'),
                'users'=>array('admin'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }
    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex()
    {
        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/main.php'
        $listIdeality = Ideality::model()->findAll();


        //$this->layout='//layouts/front_end';
        $this->render('index');
    }

    public function actionDiscover()
    {
        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/main.php'
        $listCategory = Category::model()->findAll();
        $listIdeality = Ideality::model()->findAll();

        //$this->layout='//layouts/front_end';
        $this->render('discover', array('listCategory' => $listCategory, 'listIdeality' => $listIdeality));
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError()
    {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * Displays the contact page
     */
    public function actionContact()
    {
        $model = new ContactForm;
        if (isset($_POST['ContactForm'])) {
            $model->attributes = $_POST['ContactForm'];
            if ($model->validate()) {
                $name = '=?UTF-8?B?' . base64_encode($model->name) . '?=';
                $subject = '=?UTF-8?B?' . base64_encode($model->subject) . '?=';
                $headers = "From: $name <{$model->email}>\r\n" .
                    "Reply-To: {$model->email}\r\n" .
                    "MIME-Version: 1.0\r\n" .
                    "Content-Type: text/plain; charset=UTF-8";

                mail(Yii::app()->params['adminEmail'], $subject, $model->body, $headers);
                Yii::app()->user->setFlash('contact', 'Thank you for contacting us. We will respond to you as soon as possible.');
                $this->refresh();
            }
        }
        $this->render('contact', array('model' => $model));
    }

    /**
     * Displays the login page
     */
    public function actionLogin()
    {
        $model = new LoginForm;

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login())
                $this->redirect(Yii::app()->user->returnUrl);
        }
        // display the login form
        $this->render('login', array('model' => $model));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout()
    {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

    public function actionListIdeality()
    {
        $row_length = 0;
        $criteria = new CDbCriteria();
        $criteriaTmp = new CDbCriteria();
        $params = array();
        $role = "";
        if (Yii::app()->user->isGuest) {
            $row_length = Param::SHOW_NUMBER_PROJECT_GUEST;
           // $criteria->addCondition("create_datetime <= DATE_SUB(NOW(),INTERVAL 7 DAY)");
            $criteria->order = "create_datetime asc";
        } else {
            $roles = Rights::getAssignedRoles(Yii::app()->user->Id);

            foreach ($roles as $row)
                $role = strtoupper($row->name);
            if ($role == Param::ROLE_AUTHEN) {
                $row_length = Param::SHOW_NUMBER_PROJECT_AUTHEN;
                $criteria->order = "create_datetime asc";
             //   $criteria->addCondition("create_datetime <= DATE_SUB(NOW(),INTERVAL 7 DAY)");

            } else {
                $row_length = 10000;
                $criteria->order = "create_datetime desc";
            }
            
        }
        $criteria->addCondition("id not in (select ideality_id from transaction where trans_type=".Param::TRANS_TYPE_FULL_PRICE." and trans_status=".Param::TRANS_STATUS_BUYED." )");
        $criteria->limit = $row_length;
        $criteriaTmp=$criteria;
        $criteriaTmp->params=$params;
        
        $idealityShowed=array_keys(CHtml::listData(Ideality::model()->findAll($criteriaTmp),'id','title'));
        if (isset($_REQUEST['cate_id'])) {
            $cate_id = $_REQUEST['cate_id'] ? $_REQUEST['cate_id'] : '-1';
            $criteria->addCondition("cate_id = :cate_id");
            $criteria->params['cate_id'] = $cate_id;
            
            $criteria->addInCondition('id', $idealityShowed);
            //$listIdeality = Ideality::model()->findAll('cate_id=' . $cate_id);
        } else {
            $cate_id = -1;
            //$listIdeality = Ideality::model()->findAll();
        }
        
        $listIdeality = Ideality::model()->findAll($criteria);
        $listCategory = Category::model()->findAll();
        //$this->layout='//layouts/front_end';
        $this->render('listideality', array('data' => $listIdeality, 'listCategory' => $listCategory, 'cate_id' => $cate_id,'role'=>$role));
    }

    public function actionPastIdeality()
    {
        $userId = Yii::app()->user->getId();

        $listIdeality = Ideality::model()->findAll('user_id=' . $userId);


        //$this->layout='//layouts/front_end';
        $this->render('pastideality', array('data' => $listIdeality));
    }
    public function actionConfirmOrder()
    {
        $idealityID= $_REQUEST['ideality_id'];
        $trans_type= $_REQUEST['trans_type'];
        $role = "";
        $ideality = Ideality::model()->find('id=' .$idealityID );
        $roles = Rights::getAssignedRoles(Yii::app()->user->Id);

        foreach ($roles as $row)
            $role = strtoupper($row->name);

        //$this->layout='//layouts/front_end';
        $this->render('confirmOrder', array('data' => $ideality,'trans_type'=>$trans_type,'role'=>$role));
    }
    public function actionCreateOrder()
    {
        //var_dump($_REQUEST);die();
        $idealityID= $_REQUEST['ideality_id'];
        $trans_type= $_REQUEST['trans_type'];

        $buyer_id=Yii::app()->user->id;
        $model=new Transaction;
        $model->buyer_id=$buyer_id;
        $model->ideality_id=$idealityID;
        $model->trans_type=$trans_type;
        $model->trans_status=0;

        $ideality=Ideality::model()->find('id='.$idealityID);
        $seller_id=$ideality->user_id;
        $message= new Message;
        $message->message='Your project  "'.$ideality->title.'"has been requested for buying with '.($model->trans_type==Param::TRANS_TYPE_FULL_PRICE ? ' full price':' partial price').'. Please wait for a call from admin.';
        $message->user_id=$seller_id;
        $message->ideality_id=$idealityID;
        if($model->save() & $message->save())
        {

            $this->render('createOrder',array('msg'=>'Your request to buy the project  "'.$ideality->title.'" has been sent for review. Please check your message inbox regularly for any update.'));
        }
        else{
            $this->render('createOrder',array('msg'=>'Your transaction are not successful'));
        }

        //$this->layout='//layouts/front_end';
    }
    public function actionTransaction()
    {
        $buyer_id=Yii::app()->user->id;
        $model=Transaction::model()->findAll('buyer_id='.$buyer_id);
        $this->render('transaction',array(
            'data'=>$model,
        ));
    }
    public function actionMessage()
    {
        $userId = Yii::app()->user->getId();

        $listMessage = Message::model()->findAll('user_id=' . $userId);


        //$this->layout='//layouts/front_end';
        $this->render('message', array('data' => $listMessage));
    }
    public function actionDownload(){

        $ideality_id	= $_GET['ideality_id'];
        $ideality=Ideality::model()->find("id=:id",array(':id'=>$ideality_id));
        $file_name=$ideality->file_attach;
        if( file_exists( 'FileAttack/'.$file_name ) ){
            Yii::app()->getRequest()->sendFile( $file_name , file_get_contents( 'FileAttack/'.$file_name ) );
        }
        else{
            $this->render('download404');
        }
    }
}